###############################################################################
# SNOW.R
#
# Distributes simulations to different CPUs
#
# Last edited: 14 January 2015 by Roni 
###############################################################################

rm(list = ls(all = TRUE))

args <- commandArgs()

library(snowfall)
sfSetMaxCPUs(number=80)
socketHosts <- unlist(strsplit(args[4], ","))
socketHosts <- substr(socketHosts, 1, nchar(socketHosts)-3)
print(length(socketHosts))

cpus <- length(socketHosts) #number of CPUs to use 
input.list <- as.list(seq_len(350))

sfInit(type="SOCK", socketHosts=socketHosts, parallel=TRUE, cpus=cpus) #start cluster 
 sfLibrary(data.table)               #load packages on slaves
 sfSource("analysis/make_ensemble.R")
 sfClusterApplyLB(input.list, make_ensemble) 
 sfStop() # this stops the clusterprint("FINISHED")
print(Sys.time())

ensemble <- list()
for (i in c(1, 1:350)) {
 ensemble[[i]] <- readRDS(paste0("results_combined/ensemble",i,".rds"))
}
ensemble <- rbindlist(ensemble)
save(ensemble, file="ensemble.Rdata")

